package stud.mpgame.old.game;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import stud.mpgame.network.Message;
import stud.mpgame.network.UserObject;
import stud.mpgame.utils.ICloneable;

public class Player extends UserObject implements ICloneable {

    private static final int NUMBER_OF_PROCESSED_KEYS = 4;

    //0 - up, 1 - right, 2 - down, 3 - left
    private boolean[] pressed = new boolean[NUMBER_OF_PROCESSED_KEYS];

    private int dx[] = {0, 1, 0, -1};
    private int dy[] = {-1, 0, 1, 0};

    private float x;
    private float y;
    private static float velocity = 1/3;
    private float velocityX;
    private float velocityY;
    private int id;
    private static int lastId = 0;
    private IoSession session;

    public Player(float x, float y, IoSession session) {
        for(int i = 0; i < pressed.length; i++)
            pressed[i] = false;
        this.x = x;
        this.y = y;
        this.id = lastId;
        this.session = session;
    }

    public IoSession getSession() {
        return session;
    }

    public int getId() {
        return id;
    }

    public float getX() {
        return x;
    }

    public float getY() {
        return y;
    }

    public static void increaseLastID() {
        ++lastId;
    }

    public void applyGameCommand(GameCommand command) {
        int currentKey = command.getKeyCode();
        pressed[currentKey] = command.getKeyStatus();
    }

    public void move(int time) {
        for(int i = 0; i < pressed.length; i++) {
            if(pressed[i]) {
                x += dx[i] * time;
                y += dy[i] * time;
                velocityX += dx[i] * velocity;
                velocityY += dy[i] * velocity;
            }
        }
    }

    @Override
    public void writeExternal(IoBuffer buffer, Message owner) {
    	buffer.putInt(id);
    	buffer.putFloat(x);
    	buffer.putFloat(y);
        buffer.putFloat(velocityX);
        buffer.putFloat(velocityY);
    }

    public ICloneable getClone() {
        Player player = new Player(x, y, session);
        player.id = id;
        for(int i = 0; i < pressed.length; i++)
            player.pressed[i] = pressed[i];
        return player;
    }

}
